<template>
  <div class="warpper">
    <div class="toolbar">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline" label-width="auto" label-position="right">
        <el-form-item label="Quotation  Number">
          <el-input v-model="searchForm.ordernumber" @keyup.enter.native="search" placeholder="Enter NO">
          </el-input>
        </el-form-item>


        <el-form-item label="Customer">
          <el-input v-model="searchForm.customername" placeholder="Enter Name">
          </el-input>
        </el-form-item>

        <el-form-item label="Status" prop="status">
          <el-select v-model="searchForm.status" placeholder="Select status">
            <el-option v-for="item in status" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="Salesperson" prop="staff">
          <el-select v-model="searchForm.staff" placeholder="Select Staff">
            <el-option v-for="item in staff" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <br />

        <el-form-item label="CustomerID">
          <el-input v-model="searchForm.customer_id" placeholder="Enter customerid">
          </el-input>
        </el-form-item>

        <el-form-item label="Product">
          <el-input v-model="searchForm.productname" placeholder="Enter productname">
          </el-input>
        </el-form-item>

        <el-form-item label="Created Time" prop="created_at">
          <el-date-picker v-model="searchForm.created_at" type="datetimerange" range-separator="-"
            start-placeholder="Select Start Date" end-placeholder="Select End Date" value-format="yyyy-MM-dd"
            style="width: 140.8%;">
          </el-date-picker>
        </el-form-item>
        <br />
        <el-form-item>
          <el-button @click="find()" plain style="margin-left: 24px;">Search</el-button>
          <el-button v-permission="['quotationlists.store']" type="primary" plain @click="stockinadd()">+
            New</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table">

      <el-table @sort-change="handleSortChange" :data="tableData" size="small" stripe border style="width: 100%" align="center">

        <el-table-column type="selection" width="50" align="center" />

        <el-table-column prop="ordernumber" label="Number" min-width="120" align="center" sortable="ordernumber" />

        <el-table-column prop="status" label="Status" width="100" sortable />

        <el-table-column prop="customername" label="Customer" width="190" align="center" sortable="customername">
          <template v-slot="scope">
            <span>{{ scope.row.customername }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="customerid" label="CustomerID" width="190" align="center" sortable="customerid">
          <template v-slot="scope">
            <span>{{ scope.row.customerid }}</span>
          </template>
        </el-table-column>


        <el-table-column prop="items" label="Items" width="100" align="center" sortable>
          <template v-slot="scope">
            <span>{{ scope.row.items }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="created_at" label="Created Time" min-width="120" align="center" sortable="created_at">
          <template v-slot="scope">
            <span>{{ scope.row.created_at | showDateTime }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="validityday" label="Quotation Validity(Day)" width="200" align="center" sortable>
          <template v-slot="scope">
            <span>{{ scope.row.validityday }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="currency" label="Currency" width="140" align="center" sortable="currency">
          <template v-slot="scope">
            <span>{{ scope.row.currency }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="tel" label="Tel" width="120" align="center" sortable="tel">
          <template v-slot="scope">
            <span>{{ scope.row.tel }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="staff" label="Salesperson" width="120" align="center" sortable>
          <template v-slot="scope">
            <span>{{ scope.row.staff }}</span>
          </template>
        </el-table-column>

        <el-table-column label="Actions" width="100">
          <template slot-scope="scope">
            <el-button size="mini" v-permission="['quotationlists.show']" plain
              @click="edit(scope.row.id)">View</el-button>
          </template>
        </el-table-column>
      </el-table>

    </div>
    <div class="page">
      <el-pagination v-if="isPaginate" background :current-page="page.current_page" :page-sizes="page.sizes"
        :page-size="page.per_page" layout="prev, pager, next" :total="page.total" @size-change="sizeChange"
        @current-change="currentChange" />
    </div>

  </div>
</template>

<script>
import CURD from "@/mixin/CURD";
import {
  index as adminindex
} from "@/api/admin";
export default {
  name: "quotationlistIndex",
  mixins: [CURD],
  components: {},
  data() {
    return {
      formData: {},
      staff: [{
        id: null,
        name: "All",
      }],
      status: [{
        id: null,
        name: "All",
      },
      {
        id: "pending",
        name: "pending",
      }, {
        id: "approved",
        name: "approved",
      },
      {
        id: "rejection",
        name: "rejection",
      },
      {
        id: "shipment_completed",
        name: "voided",
      }
      ],
      module: "quotationlist",
      newTitle: "New quotationlist",
      editTitle: "Edit quotationlist",
      isPaginate: true,
      isUploadFile: false,
      isShow: false,
      imageUrl: "",
      deptOptions: [],
      searchForm: {

      },
    };
  },
  async created() {
    try {
      const {
        data
      } = await adminindex(1, 100, {
        usertype: 1
      });
      this.staff = data.map(item => ({
        id: item.nickname, // 将 nickname 的值赋给 id
        name: item.nickname // 将 nickname 的值赋给 name
      }));

      // 在数组最前面添加一个特定的对象
      this.staff.unshift({
        id: null,
        name: 'ALL'
      });
    } catch (error) {
      console.error('Failed to fetch staff:', error);
    }
  },
  methods: {
    handleSortChange({ column, prop, order }) {
      this.searchForm.sort_field = prop;
      this.searchForm.sort_order = order === 'ascending' ? 'asc' : 'desc';
      this.fetchData();
    },
    async fetchData() {
      let { index } = require(`@/api/${this.module}`);
      const res = await index(
        this.page.current_page,
        this.page.per_page,
        this.searchForm  // 包含了排序参数
      );
      if (
        res.data instanceof Object &&
        typeof this.transfromData === "function"
      ) {
        let data = this.transfromData(res.data);
        this.tableData = data;
      } else {
        this.tableData = res.data;
      }
      if (res.meta) {
        // 分页
        res.meta.per_page = parseInt(res.meta.per_page);
        this.page = Object.assign(this.page, res.meta);
      } else {
        this.isPaginate = false; // 不分页
      }
    },
    stockinadd() {
      this.$router.push({
        path: '/quotationlist/quotationlistadd',
        query: {
          id: null
        }
      })
    },
    edit(id) {
      this.$router.push({
        path: '/quotationlist/editquotationlist',
        query: {
          id: id
        }
      })
    },
    onOpen(id) { // 展开
      this.currentOpen = id;
    },
    onClose(id) { // 关闭
      if (this.currentOpen === id) {
        this.currentOpen = null;
      }
    },
    normalizer(node) {
      if (node.children && node.children.length === 0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    handleTree(data, id, parentId, children) {
      let config = {
        id: id || 'id',
        parentId: parentId || 'parentId',
        childrenList: children || 'children'
      };

      var childrenListMap = {};
      var nodeIds = {};
      var tree = [];

      for (let d of data) {
        let parentId = d[config.parentId];
        if (childrenListMap[parentId] == null) {
          childrenListMap[parentId] = [];
        }
        nodeIds[d[config.id]] = d;
        childrenListMap[parentId].push(d);
      }

      for (let d of data) {
        let parentId = d[config.parentId];
        if (nodeIds[parentId] == null) {
          tree.push(d);
        }
      }

      for (let t of tree) {
        adaptToChildrenList(t);
      }

      function adaptToChildrenList(o) {
        if (childrenListMap[o[config.id]] !== null) {
          o[config.childrenList] = childrenListMap[o[config.id]];
        }
        if (o[config.childrenList]) {
          for (let c of o[config.childrenList]) {
            adaptToChildrenList(c);
          }
        }
      }
      return tree;
    },
    adjustOrder(row) {
      row.isEdit = true;
    },
    async saveOrder(row) {
      let data = {
        id: row.id,
        order: row.order,
        action: "order"
      };
      row.isEdit = false;
      let {
        info
      } = await update(data);
      this.fetchData();
    },
    transfromData(data) {
      let result = data.map((item) => {
        item.isEdit = false;
        return item;
      });
      return result;
    },
    saveHandle(form) {
      this.$refs[form].validate(async (valid) => {
        if (valid) {
          if (this.isUploadFile) {
            // 更改了图片，则必须先传图片
            this.$refs.uploadAvatar.submit();
          } else {
            this.save(form);
          }
        } else {
          this.$message.error("Data filling error, please fill in again according to the requirements");
        }
      });
    },
    async avatarUpload(options) {
      const file = options.file;
      if (file) {
        this.fileReader.readAsDataURL(file);
      }
      this.fileReader.onload = async () => {
        const formData = new FormData();
        formData.append("file", file);
        uploadImg(formData)
          .then((res) => {
            const {
              data
            } = res;
            this.formData.image = data.url;
            this.save("ruleForm");
          })
          .catch((err) => {
            options.onError(err);
          });
      };
    },
    changeAvatar(file, fileList) {
      const reader = new window.FileReader();
      reader.readAsDataURL(new Blob([file.raw]));
      reader.onload = (e) => {
        this.formData.image = reader.result;
        this.imageUrl = reader.result;
        this.isUploadFile = true;
      };
    },
    async changeStatus(row) {
      let tips = "";
      if (row.status) {
        tips = "是否启用该文章?";
      } else {
        tips = "是否禁用该文章?";
      }
      this.$confirm(tips, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          let data = {
            id: row.id,
            status: row.status,
            action: "status"
          };
          let {
            info
          } = await update(data);
          this.$message.success(info);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "Cancelled deletion"
          });
        });
    }
  }
}
</script>
<style>
.customWidth {
  width: 80%;
}
</style>
<style>
.table,
.toolbar,
.page {
  margin: 20px;
}

.toolbar {
  margin-top: 10px;
  padding: 5px;
}

.table {
  margin-bottom: 10px;
}

.page {
  margin-top: 10px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  line-height: 78px;
  text-align: center;
}

.green-text {
  color: green;
}

.red-text {
  color: red;
}

.yellow-text {
  color: yellow;
}
</style>